<template>
  <div class="profile-test">
    <h2>个人中心功能测试</h2>
    
    <div class="test-section">
      <h3>API接口测试</h3>
      
      <div class="test-group">
        <h4>1. 获取用户信息测试</h4>
        <el-form :model="getUserForm" label-width="120px">
          <el-form-item label="用户ID">
            <el-input v-model="getUserForm.userId" placeholder="输入用户ID" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="testGetUser" :loading="loading.getUser">
              获取用户信息
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="test-group">
        <h4>2. 更新个人资料测试</h4>
        <el-form :model="updateProfileForm" label-width="120px">
          <el-form-item label="用户ID">
            <el-input v-model="updateProfileForm.id" placeholder="输入用户ID" />
          </el-form-item>
          <el-form-item label="真实姓名">
            <el-input v-model="updateProfileForm.realName" placeholder="输入真实姓名" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="updateProfileForm.email" placeholder="输入邮箱" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="updateProfileForm.mobile" placeholder="输入手机号" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="testUpdateProfile" :loading="loading.updateProfile">
              更新个人资料
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="test-group">
        <h4>3. 修改密码测试</h4>
        <el-form :model="changePasswordForm" label-width="120px">
          <el-form-item label="原密码">
            <el-input v-model="changePasswordForm.oldPassword" type="password" placeholder="输入原密码" />
          </el-form-item>
          <el-form-item label="新密码">
            <el-input v-model="changePasswordForm.newPassword" type="password" placeholder="输入新密码" />
          </el-form-item>
          <el-form-item label="确认密码">
            <el-input v-model="changePasswordForm.confirmPassword" type="password" placeholder="确认新密码" />
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="testChangePassword" :loading="loading.changePassword">
              修改密码
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="result-section" v-if="testResult">
      <h3>测试结果</h3>
      <div class="result-content">
        <div class="result-header">
          <span class="result-status" :class="testResult.success ? 'success' : 'error'">
            {{ testResult.success ? '成功' : '失败' }}
          </span>
          <span class="result-time">{{ testResult.timestamp }}</span>
        </div>
        <div class="result-data">
          <pre>{{ JSON.stringify(testResult.data, null, 2) }}</pre>
        </div>
      </div>
    </div>

    <div class="navigation-section">
      <h3>功能导航</h3>
      <div class="nav-buttons">
        <el-button type="primary" @click="goToProfile">
          访问个人中心页面
        </el-button>
        <el-button type="info" @click="goToUserManagement">
          访问用户管理页面
        </el-button>
        <el-button @click="goToRouteTest">
          返回路由测试页面
        </el-button>
      </div>
    </div>

    <div class="info-section">
      <h3>功能说明</h3>
      <div class="info-content">
        <h4>个人中心功能特性：</h4>
        <ul>
          <li><strong>个人信息展示</strong> - 显示用户基本信息、角色、分组等</li>
          <li><strong>资料编辑</strong> - 支持修改真实姓名、邮箱、手机号</li>
          <li><strong>密码修改</strong> - 基于安全验证的密码修改功能</li>
          <li><strong>头像上传</strong> - 支持头像图片上传和更新</li>
          <li><strong>响应式设计</strong> - 适配桌面端、平板端、移动端</li>
        </ul>

        <h4>安全特性：</h4>
        <ul>
          <li><strong>密码强度验证</strong> - 新密码必须包含数字和字母，长度6-20位</li>
          <li><strong>原密码验证</strong> - 修改密码时需要验证原密码</li>
          <li><strong>Token验证</strong> - 所有操作基于用户登录Token</li>
          <li><strong>文件类型验证</strong> - 头像上传限制文件类型和大小</li>
        </ul>

        <h4>API接口：</h4>
        <ul>
          <li><code>GET /api/user/{id}</code> - 获取用户详细信息</li>
          <li><code>PUT /api/user</code> - 更新用户基本信息</li>
          <li><code>PUT /api/user/change-my-password</code> - 修改密码</li>
          <li><code>POST /api/user/avatar</code> - 上传头像</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { userAPI } from '@/api/user'
import { profileAPI } from '@/api/profile'

const router = useRouter()

// 加载状态
const loading = reactive({
  getUser: false,
  updateProfile: false,
  changePassword: false
})

// 测试结果
const testResult = ref(null)

// 获取用户信息表单
const getUserForm = reactive({
  userId: ''
})

// 更新个人资料表单
const updateProfileForm = reactive({
  id: '',
  realName: '',
  email: '',
  mobile: ''
})

// 修改密码表单
const changePasswordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 设置测试结果
const setTestResult = (success, data, message = '') => {
  testResult.value = {
    success,
    data: success ? data : { error: message || data },
    timestamp: new Date().toLocaleString('zh-CN')
  }
}

// 测试获取用户信息
const testGetUser = async () => {
  if (!getUserForm.userId) {
    ElMessage.error('请输入用户ID')
    return
  }

  loading.getUser = true
  try {
    const response = await userAPI.getUserById(parseInt(getUserForm.userId))
    
    if (response.success) {
      setTestResult(true, response.data)
      ElMessage.success('获取用户信息成功')
    } else {
      setTestResult(false, response, response.message)
      ElMessage.error('获取用户信息失败: ' + response.message)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    setTestResult(false, error.message, '请求失败')
    ElMessage.error('请求失败: ' + error.message)
  } finally {
    loading.getUser = false
  }
}

// 测试更新个人资料
const testUpdateProfile = async () => {
  if (!updateProfileForm.id) {
    ElMessage.error('请输入用户ID')
    return
  }

  loading.updateProfile = true
  try {
    const updateData = {
      id: parseInt(updateProfileForm.id),
      realName: updateProfileForm.realName || undefined,
      email: updateProfileForm.email || undefined,
      mobile: updateProfileForm.mobile || undefined
    }

    console.log('发送更新数据:', updateData)

    const response = await userAPI.updateUser(updateData)
    
    if (response.success) {
      setTestResult(true, response.data)
      ElMessage.success('更新个人资料成功')
    } else {
      setTestResult(false, response, response.message)
      ElMessage.error('更新个人资料失败: ' + response.message)
    }
  } catch (error) {
    console.error('更新个人资料失败:', error)
    setTestResult(false, error.message, '请求失败')
    ElMessage.error('请求失败: ' + error.message)
  } finally {
    loading.updateProfile = false
  }
}

// 测试修改密码
const testChangePassword = async () => {
  if (!changePasswordForm.oldPassword || !changePasswordForm.newPassword || !changePasswordForm.confirmPassword) {
    ElMessage.error('请填写完整的密码信息')
    return
  }

  if (changePasswordForm.newPassword !== changePasswordForm.confirmPassword) {
    ElMessage.error('新密码和确认密码不一致')
    return
  }

  // 验证密码强度
  const password = changePasswordForm.newPassword
  if (password.length < 6 || password.length > 20) {
    ElMessage.error('密码长度必须在6-20位之间')
    return
  }

  const hasDigit = /\d/.test(password)
  const hasLetter = /[a-zA-Z]/.test(password)
  if (!hasDigit || !hasLetter) {
    ElMessage.error('密码必须包含数字和字母')
    return
  }

  loading.changePassword = true
  try {
    const response = await profileAPI.changeCurrentUserPassword({
      oldPassword: changePasswordForm.oldPassword,
      newPassword: changePasswordForm.newPassword,
      confirmPassword: changePasswordForm.confirmPassword
    })
    
    if (response.success) {
      setTestResult(true, response.data)
      ElMessage.success('修改密码成功')
      
      // 清空表单
      changePasswordForm.oldPassword = ''
      changePasswordForm.newPassword = ''
      changePasswordForm.confirmPassword = ''
    } else {
      setTestResult(false, response, response.message)
      ElMessage.error('修改密码失败: ' + response.message)
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    setTestResult(false, error.message, '请求失败')
    ElMessage.error('请求失败: ' + error.message)
  } finally {
    loading.changePassword = false
  }
}

// 导航功能
const goToProfile = () => {
  router.push('/admin/profile')
}

const goToUserManagement = () => {
  router.push('/admin/system/user')
}

const goToRouteTest = () => {
  router.push('/test/route')
}
</script>

<style scoped>
.profile-test {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-section,
.result-section,
.navigation-section,
.info-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #fafafa;
}

.test-group {
  margin-bottom: 25px;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background-color: white;
}

.test-group h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.result-content {
  background-color: white;
  border-radius: 6px;
  padding: 15px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.result-status {
  padding: 4px 12px;
  border-radius: 4px;
  font-weight: bold;
  font-size: 14px;
}

.result-status.success {
  background-color: #f0f9ff;
  color: #0ea5e9;
}

.result-status.error {
  background-color: #fef2f2;
  color: #ef4444;
}

.result-time {
  color: #666;
  font-size: 12px;
}

.result-data {
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 12px;
  overflow-x: auto;
}

.result-data pre {
  margin: 0;
  font-size: 12px;
  line-height: 1.4;
  color: #333;
}

.nav-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.info-content h4 {
  margin: 20px 0 10px 0;
  color: #333;
  font-size: 16px;
}

.info-content ul {
  margin: 0 0 15px 0;
  padding-left: 20px;
}

.info-content li {
  margin-bottom: 8px;
  line-height: 1.5;
}

.info-content code {
  background-color: #f1f5f9;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  color: #e11d48;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-button + .el-button {
  margin-left: 10px;
}

@media (max-width: 768px) {
  .profile-test {
    padding: 15px;
  }
  
  .test-section,
  .result-section,
  .navigation-section,
  .info-section {
    padding: 15px;
  }
  
  .nav-buttons {
    flex-direction: column;
  }
  
  .nav-buttons .el-button {
    margin-left: 0 !important;
  }
}
</style>